package com.hmk.blogboot.aspect;



import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/*使用Aspect实现日志处理记录访问者ip  url  调用方法*/
@Aspect     //开启切面
@Component  //添加到spring容器，springboot找到该组件
public class LogAspect {

    //定义一个日志记录器 记录LogAspect类里面的日志
     private  final Logger logger = LoggerFactory.getLogger(this.getClass());


     /*切面 请求前端到后端，响应的结果返回前端，一条流线  */

    //切面切点  用来拦截web包下的控制器类，
    @Pointcut("execution(* com.hmk.blogboot.web.*.*(..))")
    public void log(){}

    /*在切面之前执行的方法*/
    @Before("log()")
    public void  doBefore(JoinPoint joinPoint){
        //获取url ip 采用的是线程池方式进行获取request请求对象
        ServletRequestAttributes attributes  =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request  = attributes.getRequest();
       String url  =  request.getRequestURL().toString();
        String ip  =  request.getRemoteAddr();
        //使用切面里面一个joinPoint对象获取剩下的类名 方法名  参数
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        //创建内部类，接收日志收集的对象
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("Request  :  {}",requestLog);
    }

    /*在切面之前执行的方法*/
    @After("log()")
    public void  doAfter(){
        logger.info("------------------doAfter--------------------");
    }

    /*记录后端返回的响应结果*/
    /*
    *
    *1 result:接收拦截获取到的返回结果
    *2使用@AfterReturnig注解表示拦截方法取得结果值，里面指定接收拦截获取到的返回结果值的对象，切面
    * */
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}",result);
    }
    /*日志记录 请求url  访问者ip  调用方法classMethod  参数args(请求url中参数)  返回内容
    * 封装一个内部类
    * */
    private  class  RequestLog{
        private  String url;
        private String  ip;
        private String classMethod;
        private Object[]  args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }


}
